package com.liusp.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liusp.dao.SetmealAndCheckGroupDao;
import com.liusp.dao.SetmealDao;
import com.liusp.entity.PageResult;
import com.liusp.entity.QueryPageBean;
import com.liusp.pojo.Setmeal;
import com.liusp.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService{
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private SetmealAndCheckGroupDao setmealAndCheckGroupDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Setmeal setmeal,Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.先修改套餐基本信息
        setmealDao.edit(setmeal);
        //2.修改关联关系
        //2.1.先删除，再新增
        setmealAndCheckGroupDao.deleteBySetmealById(setmeal.getId());
        addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
    }

    @Override
    public void delete(Integer id) {
        //首先需要删除该套餐与检查组的关联关系
        setmealAndCheckGroupDao.deleteBySetmealById(id);
        //在删除套餐信息
        setmealDao.delete(id);
    }

    @Override
    public List<Integer> findCheckgroupIdsBySetmealId(Integer id) {
        return setmealAndCheckGroupDao.findCheckgroupIdsBySetmealId(id);
    }

    /**
     * 批量插入套餐与检查组关系
     * @param setmealId 套餐id
     * @param checkgroupIds 检查组id数组
     */
    private void addSetmealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        Arrays.stream(checkgroupIds).forEach(checkgroupId -> {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",setmealId);
            map.put("checkgroup_id",checkgroupId);
            setmealAndCheckGroupDao.batchInsert(map);
        });
    }
}
